package com.example.routelink.gateway.filter;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson2.JSON;
import com.example.routelink.gateway.entity.ResultData;
import com.example.routelink.gateway.entity.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
public abstract class BaseFilter<C> extends AbstractGatewayFilterFactory<C> implements Ordered {

    public BaseFilter(Class<C> configClass) {
        super(configClass);
    }

    public Mono<Void> response(ServerWebExchange exchange, ResultEnum resultEnum) {
        exchange.getResponse().setStatusCode(HttpStatus.OK);
        exchange.getResponse().getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        byte[] bytes = JSON.toJSONString(
                ResultData.builder().code(resultEnum.getCode()).message(resultEnum.getMsg()).build()
        ).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
        return exchange.getResponse().writeWith(Mono.just(buffer));
    }

    public void writeLog(String filterName, long startTime, String format, Object... arguments) {
        long total = System.currentTimeMillis() - startTime;
        String[] args = new String[]{filterName, String.valueOf(total)};
        log.info("[过滤器-{}] [耗时{}] " + format, ArrayUtil.addAll(args, arguments));
    }

    public boolean isGatewayCustom(String str) {
        return str.startsWith("gatewayCustom");
    }

}
